<template>
  <div ref="editorRef" class="wangeditor-container"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import E from 'wangeditor';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入内容...'
  }
});

const emits = defineEmits(['update:modelValue']);
const editorRef = ref(null);
let editor = null;

onMounted(() => {
  // 创建编辑器实例
  editor = new E(editorRef.value);
  
  // 配置编辑器
  editor.config.placeholder = props.placeholder;
  
  // 设置编辑器内容
  editor.config.onCreated = () => {
    editor.txt.html(props.modelValue);
  };
  
  // 监听内容变化
  editor.config.onChange = () => {
    const html = editor.txt.html();
    emits('update:modelValue', html);
  };
  
  // 创建并加载编辑器
  editor.create();
});

// 监听外部内容变化
watch(() => props.modelValue, (newValue) => {
  if (editor && editor.txt.html() !== newValue) {
    editor.txt.html(newValue);
  }
});

// 组件销毁前销毁编辑器
onBeforeUnmount(() => {
  if (editor) {
    editor.destroy();
    editor = null;
  }
});
</script>

<style>
.wangeditor-container {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-top: 10px;
  min-height: 600px;
}
.w-e-text-container {
 height: 600px !important; 
}
</style>